package demo.service.Impl;

import demo.dao.AccountDao;
import demo.dao.Impl.AccountDaoImpl;
import demo.entity.Account;
import demo.service.AccountService;
import demo.utils.JDBCUtils;

import java.sql.SQLException;

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao = new AccountDaoImpl();
    @Override
    public String zhuanzhang(Integer fromId, Integer toId, Double money)  {
        try {
            JDBCUtils.begin();
            //1.查询我方账户
            Account account = accountDao.selectById(fromId);
            if (account == null){
                return "我方账户不存在";
            }
            //2.查询对方账户
            if (accountDao.selectById(toId) == null){
                return "对方账户不存在";
            }
            //3.查询我方余额
            if (account.getMoney() < money){
                return "余额不足";
            }
            //4.转出我方账户
            int i = accountDao.updateById(fromId, -money);
            //5.转入对方账户
            int j = accountDao.updateById(toId, money);
            if (i == 0 || j == 0){
                return "转账失败";
            }
            JDBCUtils.commit();
            return "转账成功";
        } catch (SQLException e) {
            e.printStackTrace();
            JDBCUtils.rollback();
        }
        return "转账失败";
    }
}
